﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LSQL;
using DevExpress.CodeParser;
using DevExpress.DashboardExport;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;
using Org.BouncyCastle.Crypto;

namespace Shopfloormanagement.Forms
{
    public partial class kpiRelation : DevExpress.XtraEditors.XtraForm
    {
        public static kpiRelation instance = new kpiRelation();
        public kpiRelation()
        {
            instance = this;
            InitializeComponent();
        }

        public static string FormText = string.Empty;
        private DataTable dtRelation = new DataTable();
        private void kpiRelation_Load(object sender, EventArgs e)
        {
            gcRelation.DataSource = null;
            //写出窗体名
            this.Text = $"设置{SystemInfo.readparentDepName} {FormText} 的逻辑";
            //加载部门
            DataTable dtDep = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0 and isDisplay = 1");
            publicFunc.ComboBoxInit(dtDep, cbDepartment, "DepartmentName", "ID");

            //初始化下方
            dtRelation = new DataTable();
            dtRelation.Columns.Add("ID", typeof(int));
            dtRelation.Columns.Add("DepartmentName", typeof(string));

            dtRelation.Columns["DepartmentName"].Caption = "Department Name";

            //载入当前
            DataTable relation = SQL.ReturnDataTableDist(SystemInfo.SQL, $"DepartmentID_{FormText}", "SQDC_Relation", $"HomeDepartmentID = {SystemInfo.readparentDep}");
            if (relation.Rows.Count > 0)
            {
                string str = relation.Rows[0][$"DepartmentID_{FormText}"].ToString();
                if (str != "")
                {
                    int[] IDs = str.Split(',')
                                    .Select(s => int.Parse(s))
                                    .ToArray();
                    for (int i = 0; i < IDs.Length; i++)
                    {
                        DataTable deps = SQL.ReturnDataTableDist(SystemInfo.SQL, $"ID,DepartmentName", "Departments", $"ID = {IDs[i]}");
                        if (deps.Rows.Count <= 0)
                        {
                            return;
                        }
                        dtRelation.Rows.Add((int)deps.Rows[0]["ID"], deps.Rows[0]["DepartmentName"].ToString());

                        gcRelation.DataSource = dtRelation;
                        gvRelation.Columns["ID"].Visible = false;
                    }
                }
                else
                {
                    gcRelation.DataSource = dtRelation;
                    gvRelation.Columns["ID"].Visible = false;

                }

            }

            
        }

        private int selectDepID = -1;
        private void cbDepartment_SelectedValueChanged(object sender, EventArgs e)
        {
            // 获取选中的项的Tag
            var selectedItem = cbDepartment.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                selectDepID = Convert.ToInt32(tag);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            DataRow[] drs = (dtRelation.Rows.Count > 0) ? dtRelation?.Select($"DepartmentName = '{cbDepartment.Text}'") : new DataRow[0];
            if (selectDepID > 0 && drs.Length == 0)
            {
                dtRelation.Rows.Add(selectDepID, cbDepartment.Text);
                gcRelation.DataSource = dtRelation;
                gvRelation.Columns["ID"].Visible = false;
                gcRelation.RefreshDataSource();
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (gvRelation.RowCount > 0)
            {
                int[] idsArray = new int[gvRelation.RowCount];
                for (int i = 0; i < gvRelation.RowCount; i++)
                {
                    idsArray[i] = (int)gvRelation.GetRowCellValue(i, "ID");
                }
                string ids = string.Join(",", idsArray);
                DataTable dtRelation = SQL.ReturnDataTable3(SystemInfo.SQL, "SQDC_Relation", $"HomeDepartmentID = {SystemInfo.readparentDep}");
                if (dtRelation.Rows.Count > 0)
                {
                    //更新
                    int infoID = (int)dtRelation.Rows[0]["ID"];
                    bool res = SQL.Update(SystemInfo.SQL, "SQDC_Relation", $"DepartmentID_{FormText} = '{ids}'", $"ID = {infoID}");
                    if (res)
                    {
                        XtraMessageBox.Show(LookAndFeel, $"成功更新{SystemInfo.readparentDepName} {FormText}的逻辑");
                    }
                }
                else
                {
                    int res = SQL.InsertReturnID(SystemInfo.SQL, "SQDC_Relation", $"HomeDepartmentID,DepartmentID_{FormText}", $"{SystemInfo.readparentDep},'{ids}'");
                    if (res > 0)
                    {
                        XtraMessageBox.Show(LookAndFeel, $"成功更新{SystemInfo.readparentDepName} {FormText}的逻辑");
                    }
                }
            }

        }

        private void itemBtnDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //删除当前
            dtRelation.Rows.RemoveAt(rowIndex);
            gcRelation.RefreshDataSource();
            rowIndex = -1;
        }

        private int rowIndex = -1;
        private void gvRelation_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    rowIndex = hitInfo.RowHandle;
                    pMenuGvRelation.ShowPopup(Control.MousePosition); // 在鼠标位置显示菜单
                }
            }
        }
    }
}